﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;

using RexToy.UI.WinForm.Pmlx;
using RexToy.UI.WinForm.ViewModel;

namespace RexToy.UI.WinForm.Controls
{
    public class EnumComboBox : ComboBoxEx
    {
        public override void UpdateView(ViewModelBase model)
        {
            IReflector r = Reflector.Bind(model);
            object val = r.GetPropertyValue(BindPropertyName);
            this.InternalSetSelectedItem(val);
        }

        public override void UpdateModel(ViewModelBase model)
        {
            IReflector r = Reflector.Bind(model);
            object val = this.InternalGetSelectedItem();
            r.SetPropertyValue(BindPropertyName, val);
        }

        public void Bind<T>()
        {
            Type type = typeof(T);
            if (!type.IsEnum)
                ThrowHelper.ThrowNotEnumException(type);

            this.BindType<T>();

            Array values = Enum.GetValues(typeof(T));
            foreach (T v in values)
            {
                ComboBoxItem cbItem = new ComboBoxItem();
                cbItem.ID = v;
                cbItem.DisplayName = EnumEx.GetDescription(v as Enum);
                cbItem.Item = v;

                this.Items.Add(cbItem);
            }
        }

        protected override object InternalGetSelectedItem()
        {
            if (this.SelectedItem == null)
                return 0;
            else
            {
                var cbItem = this.SelectedItem as ComboBoxItem;
                return cbItem.Item;
            }
        }

        public override T GetSelectedItem<T>()
        {
            this.CheckGetSetType<T>();

            if (this.SelectedItem == null)
                return default(T);
            else
            {
                ComboBoxItem cbItem = this.SelectedItem as ComboBoxItem;
                return (T)cbItem.Item;
            }
        }

        protected override void InternalSetSelectedItem(object item)
        {
            int i = 0;
            for (; i < this.Items.Count; i++)
            {
                var cbItem = this.Items[i] as ComboBoxItem;
                if (item.Equals(cbItem.Item))
                {
                    SelectedIndex = i;
                    return;
                }
            }
            SelectedIndex = -1;//Note:Not selected
        }

        public override void SetSelectedItem<T>(T item)
        {
            this.CheckGetSetType<T>();

            int i = 0;
            for (; i < this.Items.Count; i++)
            {
                ComboBoxItem cbItem = this.Items[i] as ComboBoxItem;

                if (item.Equals(cbItem.Item))
                {
                    SelectedIndex = i;
                    return;
                }
            }
            SelectedIndex = -1;//Note:Not selected
        }
    }
}
